package cn.pconline.autoclub.web.wap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.entity.Area;
import cn.pconline.autoclub.service.AreaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.web.UserAuth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 *
 * area地区controller
 */
@Controller
@RequestMapping(value = "/wap/area")
public class AreaController {
	
    @Autowired
    private UserAuth userAuth;
    @Autowired 
    private MemberService memberService;
    @Autowired
    private AreaService areaService;
    
	private static final Logger log = LoggerFactory.getLogger(AreaController.class); 
	private static final String HOT = "hot";
	
    /**
     * 根据选择的大写字母获得城市列表
     * @param request
     * @param response
     */
	@ResponseBody
    @RequestMapping(value="/getCityList.do", method=RequestMethod.GET)
    public void getCityList(HttpServletRequest request, HttpServletResponse response) {
    	//获取相关参数
    	WebUtils.setEncoding4App(request, response);
        String callback = WebUtils.param(request, AppControllerStatic.APP_API_PARA_CALLBACK, "");
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        String initial = WebUtils.param(request, "initial", "");
        
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if(initial == "") {
        	printErrorMsg(response, AppUtils.STATUS_FAIL, "操作失败", callback);
            return;
        }
        List<Area> areaList = new ArrayList<Area>();
        if(HOT.equals(initial)){
        	areaList = areaService.listHotArea();
        }else{
        	areaList = areaService.listAreaByInitial(initial, Area.AREA_LEVEL2);
        }
        
        if(areaList.size() > 0){
	        for(Area area : areaList) {
	        	JSONObject json = new JSONObject();
	        	json.put("areaCode", area.getAreaCode());
	        	json.put("areaName", xssEncode == 0 ? area.getAreaName() : EncodeUtils.encodeForHTMLFilterNull(area.getAreaName()));
	        	jsonArray.add(json);
	        }
	        jsonObject.put("city", jsonArray);
        }
        printSuccessMsg(response, "操作成功", jsonObject, callback);
    }
    
	 /**
     * 获得城市
     * @param request
     * @param response
     */
	@ResponseBody
    @RequestMapping(value="/getCity.do", method=RequestMethod.GET)
    public void getCity(HttpServletRequest request, HttpServletResponse response) {
    	//获取相关参数
    	WebUtils.setEncoding4App(request, response);
        String callback = WebUtils.param(request, AppControllerStatic.APP_API_PARA_CALLBACK, "");
        long areaCode = WebUtils.paramLong(request, "areaCode", 0);
        
        JSONObject jsonObject = new JSONObject();
        Area area = areaService.findAreaByAreaCode(areaCode);
        if(area != null){
        	   jsonObject.put("cityName", area.getAreaName());
        	   jsonObject.put("cityId", area.getAreaCode());
        	   Area parentArea = areaService.findAreaById(area.getParentId());
        	   jsonObject.put("provinceId", parentArea.getAreaCode());
        	   printSuccessMsg(response, "操作成功", jsonObject, callback);
        }
        printErrorMsg(response, AppUtils.STATUS_FAIL, "操作失败", callback);
        
    }
	 /**
     * 去到选择城市页面
     * @param request
     * @param response
     */
    @RequestMapping(value="/goSelectCity.do", method=RequestMethod.GET)
    public String goSelectCity(HttpServletRequest request, HttpServletResponse response) {
        List<Area> areas = areaService.listHotArea();
        request.setAttribute("areas", areas);
        return "template/wap/club/selectCity";
        
    }
    private void printSuccessMsg(HttpServletResponse resp, String msg, JSONObject data, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", AppUtils.STATUS_OK);
        if (StringUtils.isNotEmpty(msg)) {
            json.put("message", msg);
        }
        if (data != null) {
            json.put("data", data);
        }
        printMsg(resp, json.toJSONString(), callback);
    }
    
    private void printErrorMsg(HttpServletResponse resp, int code, String msg, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("message", msg);
        printMsg(resp, json.toJSONString(), callback);
    }

    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }
}
